package com.example.common.component;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.jetbrains.annotations.NotNull;

import java.text.ParseException;

import lombok.SneakyThrows;

public abstract class RecyclerOnScrollListener extends RecyclerView.OnScrollListener {
    //是否向上滑动
    private boolean isSlidingUpward = false;

    @SneakyThrows
    @Override
    public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        LinearLayoutManager manager=(LinearLayoutManager)recyclerView.getLayoutManager();
        //多一层判断防止报错
        if(manager==null)return;
        //获取完全显示的第一个itemPosition
        int first=manager.findFirstVisibleItemPosition();
        //当不滑动时
        if(newState==RecyclerView.SCROLL_STATE_IDLE){
            //获取最后一个完全显示的itemPosition
            int last=manager.findLastCompletelyVisibleItemPosition();

            int itemCount=manager.getItemCount();
            //展示顶部时间
            showTopData(first);

            //判断是否滑动到了最后一个item，并且是向上滑动
            if(last==(itemCount-1)&&isSlidingUpward){
                //加载更多
                loadMore();
            }
        }
        //当滑动时
        if(newState==RecyclerView.SCROLL_STATE_DRAGGING){
            showTopData(first);
        }
    }

    @SneakyThrows
    @Override
    public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
        isSlidingUpward = dy > 0;
        //滚动时改变
        LinearLayoutManager manager=(LinearLayoutManager)recyclerView.getLayoutManager();
        if (manager==null)return;
        int first=manager.findFirstVisibleItemPosition();
        showTopData(first);
    }

    public abstract void loadMore();

    public abstract void showTopData(int position) throws ParseException;
}
